import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ChatChannel implements Runnable {
    //定义一个包含所有<客户端姓名，客户端输出流>键值对的集合对象allMap,为所有ChatChannel对象共享
    private static Map<String,ObjectOutputStream> allMap=new HashMap<String,ObjectOutputStream>();
    private Socket socket;
    private ObjectInputStream ois;
    private String name;
    private ObjectOutputStream oos;

    public ChatChannel(Socket socket){
        this.socket=socket;
    }
    public void run() {
        try {
            recvNameAndEchoHello();

            while(true){
                String msg= (String) ois.readObject();
                //增加判断是否私聊的代码
                int start = msg.indexOf("@")+1;
                int end = msg.indexOf("#");
                if(start>0&&end>start){
                    //获取私聊对象名称
                    String secretName=msg.substring(start,end);
                    String secretMsg=msg.substring(end+1);
                    //调用发送私聊消息的方法
                    sendSecretMsg(secretName,secretMsg);
                }
                else {
                    //转发非私聊消息给所有客户端
                    System.out.println(name + "说:" + msg);
                    sendToAll(name + "说:" + msg);
                }
            }
        } catch (IOException e) {
            //处理客户端退出
            allMap.remove(name);
            System.out.println(name+"退出聊天室");
            try {
                sendToAll("系统消息："+name+"退出聊天室");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //定义群发消息的方法
    private void sendToAll(String s) throws IOException {
        for(ObjectOutputStream os:allMap.values()){
            os.writeObject(s);
            os.flush();
        }
    }

    private void recvNameAndEchoHello() throws IOException, ClassNotFoundException {
        InputStream is= socket.getInputStream();
        ois = new ObjectInputStream(is);
        //获得客户端输入的姓名
        name = (String) ois.readObject();

        //输出客户端进入聊天室的提示信息
        System.out.println(name +"进入聊天室");
        //调用群发消息给所有客户端的方法发送客户端进入聊天室的系统消息
        sendToAll("系统消息："+name+"进入聊天室");

        OutputStream os=socket.getOutputStream();
        oos = new ObjectOutputStream(os);

      //将<客户端的名称,客户端输出流对象>这个键值对添加到allMap中
        allMap.put(name,oos);
        //调用对象流的writeObject()方法向客户端发送欢迎信息
        oos.writeObject(name + "，您好!欢迎您进入聊天室");
        oos.flush();
    }

    private void sendSecretMsg(String secretName,String msg) throws IOException {
        //获得私聊对象的输出流对象
        ObjectOutputStream secretOOS=allMap.get(secretName);
        System.out.println(name+"悄悄地对"+secretName+"说:"+msg);
        secretOOS.writeObject(name+"悄悄地对您说:"+msg);
        secretOOS.flush();
    }
}
